﻿using System.Threading.Tasks;
using MongoDB.Driver;
using WebIM.API.Entities;
using WebIM.API.Utilities;

namespace WebIM.API.Services
{
    /// <summary>
    /// 账户服务实现
    /// </summary>
    public class ImAccountService : IImAccountService
    {
        private readonly IMongoCollection<ImAccount> _collection;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="settings">mongodb connection</param>
        public ImAccountService(IMyMongoDatabaseSettings settings)
        {
            var client = new MongoClient(settings.ConnectionString);
            var database = client.GetDatabase(settings.DatabaseName);
            _collection = database.GetCollection<ImAccount>(nameof(ImAccount));
        }

        /// <inheritdoc />
        public async Task<ImAccount> AddSync(ImAccount account)
        {
            await _collection.InsertOneAsync(account);
            return account;
        }

        /// <inheritdoc />
        public async Task<int> UpdateTokenAsync(string appKey, string token, int expiresIn, string uuid)
        {
            var filter = Builders<ImAccount>.Filter.Eq("AppKey", appKey);
            var update = Builders<ImAccount>.Update.Set("AccessToken", token)
                .Set("Application", uuid)
                .Set("ExpiresIn", expiresIn)
                .Set("ExpiredAt", DateUtils.TimestampAfterSeconds(expiresIn) - 15 * 60)
                .Set("UpdatedAt", DateUtils.Timestamp());
            // 更新AccessToken
            var result = await _collection.UpdateOneAsync(filter, update);
            return (int) result.ModifiedCount;
        }

        /// <inheritdoc />
        public async Task<ImAccount> GetAsync(string appKey)
        {
            return await _collection.FindAsync(account => account.AppKey == appKey)
                .Result.FirstOrDefaultAsync();
        }
    }

    /// <summary>
    /// 账户服务接口
    /// </summary>
    public interface IImAccountService
    {
        /// <summary>
        /// 添加账户
        /// </summary>
        /// <param name="account">账户信息</param>
        /// <returns>account</returns>
        Task<ImAccount> AddSync(ImAccount account);

        /// <summary>
        /// 更新令牌
        /// </summary>
        /// <param name="appKey">APP Key</param>
        /// <param name="token">访问令牌</param>
        /// <param name="expiresIn">过期时长</param>
        /// <param name="uuid">APP UUID</param>
        /// <returns></returns>
        Task<int> UpdateTokenAsync(string appKey, string token, int expiresIn, string uuid);

        /// <summary>
        /// 获取IM账号
        /// </summary>
        /// <param name="appKey">应用APP Key</param>
        /// <returns>返回第一条记录</returns>
        #nullable enable
        Task<ImAccount?> GetAsync(string appKey);
    }
}